#include "../include/Thread.h"
#include <stdio.h>
#include <string.h>

namespace myNameSpace {
Thread::Thread(TaskCallback &&taskCallback): _threadId(0), _isRunning(false), _taskCallback(std::move(taskCallback)) {}

void Thread::start() {
    if (!_isRunning) {
        int ret = pthread_create(&_threadId, nullptr, start_routine, this);
        if (ret) {
            fprintf(stderr, "%s\n", strerror(ret));
            return;
        }
        _isRunning = true;
    }
}

void Thread::join() {
    if (_isRunning) {
        pthread_join(_threadId, nullptr);
        _isRunning = false;
    }
}

void * Thread::start_routine(void *arg) {
    Thread *pThread = static_cast<Thread *>(arg);
    if (pThread) {
        pThread->_taskCallback();
    }
    return nullptr;
}

} // end of namespace myNameSpace
